package cmd

import (
	"context"
	"github.com/spf13/cobra"
	"go.mongodb.org/mongo-driver/mongo/readpref"
	"log"
	"time"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var url string

var mongoCmd = &cobra.Command{
	Use:   "mongo",
	Short: "mongo cluster check tool",
	Long: `mongo cluster check tool,it's will write mognodb doc'`,
	Run: func(cmd *cobra.Command, args []string)  {
		// Do Stuff Here
		log.Println("mongo command run")
		runMongoCommand(url)
	},
}

func init() {
	mongoCmd.Flags().StringVarP(&url, "url", "u", "", "mongo cluster urls")

	rootCmd.AddCommand(mongoCmd)
}
func runMongoCommand(url string)  {
	client, err := mongo.NewClient(options.Client().ApplyURI(url))
	if err != nil {
		log.Fatal(err)
	}

	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	err = client.Connect(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Disconnect(ctx)

	err = client.Ping(ctx, readpref.Primary())
	if err != nil {
		log.Fatal(err)
	}

	log.Println("ok")


}



